package com.smedi.ismedi.authoritymanagement.core.domain.service.impl;

import com.smedi.ismedi.authoritymanagement.core.domain.aggregatemodel.PinyinCount;
import com.smedi.ismedi.authoritymanagement.core.domain.repository.PinyinCountRepository;
import com.smedi.ismedi.authoritymanagement.core.domain.service.PinyinCountDomainService;
import com.smedi.ismedi.authoritymanagement.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.web.starter.util.PinyinUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: xulinjun
 * @Date: 2021-6-15 13:22
 */
@Slf4j
@Service
@AllArgsConstructor
public class PinyinCountDomainServiceImpl implements PinyinCountDomainService {
    private final PinyinCountRepository pinyinCountRepository;

    private final PinyinUtil pinYinUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String generateUserName(String LastName) throws BadHanyuPinyinOutputFormatCombination {
        String pinyin = pinYinUtil.getEname(LastName).toLowerCase();
        PinyinCount pinyinCount = pinyinCountRepository.selectByPinyin(pinyin);
        if (pinyinCount != null) {
            pinyinCount.setCount(pinyinCount.getCount() + ConstantField.pingyinIncrease);
        } else {
            pinyinCount = new PinyinCount()
                    .setPinyin(pinyin)
                    .setCount(ConstantField.pingyinIncrease);
        }
        // 保存数据
        if (pinyinCount.getCountId() == null) {
            pinyinCountRepository.doInsert(pinyinCount);
        } else {
            pinyinCountRepository.doUpdate(pinyinCount);
        }
        return pinyin + String.format("%03d", pinyinCount.getCount());
    }
}
